<template>
  <el-card shadow="never"
           class="aui-card--fill">
    <div class="mod-sys__role">
      <el-form :inline="true"
               :model="dataForm"
               @submit.native.prevent>
        <el-form-item>
          <el-input v-model="dataForm.name"
                    :placeholder="$t('role.name')"
                    @keyup.enter.native="getDataList()"
                    clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button size="small"
                     @click="getDataList()">{{ $t('query') }}</el-button>
        </el-form-item>
        <el-form-item>
          <el-button v-if="$hasPermission('sys:role:save')"
                     type="primary"
                     size="small"
                     @click="addOrUpdateHandle()">{{ $t('add') }}</el-button>
        </el-form-item>

        <el-form-item style="float: right">
          <div class="grantBtnGroup">
            <div class="grantBtn"
                 :class="{disable: !checked}"
                 v-loading="grantAccessLoading"
                 @click="openForm">Grant Access</div>
            <el-tooltip :open-delay="1000"
                        class="item"
                        effect="dark"
                        content="If account access is turn on, none of the MSPbots employees will be able to access your data without your explecit approval, please go to account access to grant access to MSPbots employees if you need support."
                        placement="bottom">
              <i class="el-icon-question"></i>
            </el-tooltip>
            <el-switch v-model="checked"
                       @change="saveClientPortalSetting"></el-switch>
          </div>
          <!--          <el-button :disabled="!checked" v-loading="grantAccessLoading" style="margin-left: 20px" type="primary" size="small" @click="openForm">Grant Access</el-button>-->
        </el-form-item>
        <!-- <el-form-item>
          <el-button v-if="$hasPermission('sys:role:delete')"
                     type="danger"
                     size="small"
                     @click="deleteHandleSelf()">{{ $t('deleteBatch') }}</el-button>
        </el-form-item> -->
      </el-form>
      <el-table v-loading="dataListLoading"
                :data="dataList"
                border
                @selection-change="dataListSelectionChangeHandle"
                @sort-change="dataListSortChangeHandle"
                style="width: 100%;">
        <el-table-column type="selection"
                         :selectable='isDisabledSelectable'
                         header-align="center"
                         align="center"
                         width="50"></el-table-column>
        <el-table-column prop="name"
                         :label="$t('role.name')"
                         header-align="center"
                         align="center"></el-table-column>
        <el-table-column prop="remark"
                         :label="$t('role.remark')"
                         header-align="center"
                         align="center"></el-table-column>
        <el-table-column prop="createDate"
                         :label="$t('role.createDate')"
                         sortable="custom"
                         header-align="center"
                         align="center"
                         width="180">
          <template slot-scope="scope">
            {{ scope.row.createDate | ClientFormat }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('handle')"
                         fixed="right"
                         header-align="center"
                         align="center"
                         width="150">
          <template slot-scope="scope">
            <el-button v-if="scope.row.id === '0'&&$hasPermission('sys:role:update')"
                       type="text"
                       size="small"
                       @click="addOrUpdateHandle(scope.row.id, scope.row.roleId)">{{ $t('update') }}</el-button>
            <el-button v-if="scope.row.id === '0'&&$hasPermission('sys:role:delete')"
                       type="text"
                       size="small"
                       @click="deleteHandleSelf(scope.row.id, scope.row.roleId)">{{ $t('delete') }}</el-button>
            <el-button type="text"
                       size="small"
                       v-if="$hasPermission('sys:role:view')"
                       @click="addOrUpdateHandle(scope.row.id, scope.row.roleId,'View')">{{ $t('custom.dataset.viewbtn') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination :current-page="current"
                     :page-sizes="[10, 20, 50, 100]"
                     :page-size="size"
                     :total="total"
                     layout="total, sizes, prev, pager, next, jumper"
                     @size-change="pageSizeChangeHandle"
                     @current-change="pageCurrentChangeHandle">
      </el-pagination>
      <add-or-update v-if="addOrUpdateVisible"
                     ref="addOrUpdate"
                     @refreshDataList="getDataList"></add-or-update>
    </div>
    <role-grant-access ref="userFormDialog"
                       :userformDialogData="userFormDialogData"
                       width="550px"></role-grant-access>
  </el-card>
</template>

<script>
import mixinViewModule from '@/mixins/view-module-plus'
import AddOrUpdate from './role-add-or-update'
import roleGrantAccess from '@/views/modules/sys/role-grant-access'
import config from '@/utils/config'
import { get } from 'lodash'
import { fetchSetting, setSetting } from '@/api/new'

export default {
  mixins: [mixinViewModule],
  data () {
    return {
      mixinViewModuleOptions: {
        getDataListURL: '/web/um/sys/role/client/client-role-page-query',
        getDataListIsPage: true,
        deleteURL: '/web/um/sys/role',
        deleteIsBatch: true
      },
      dataForm: {
        name: ''
      },
      grantAccessLoading: false,
      checked: false,
      userFormDialogData: {
        isNew: true,
        formTitle: null,
        formCode: null,
        id: null
      }
    }
  },
  components: {
    AddOrUpdate,
    roleGrantAccess
  },
  created () {
    this.getClientPortalSetting()
  },
  methods: {
    openForm () {
      if (!this.checked) return false
      this.grantAccessLoading = true
      const params = { current: 1, size: 1, desc: 'create_time', formCode: config.grantAccessFormCode }
      this.$interface.reports.getFormDataListApi(params).then(res => {
        this.grantAccessLoading = false
        if (res.data.data.records.length > 0) {
          this.userFormDialogData = {
            isNew: false,
            formTitle: 'Grant Access',
            formCode: config.grantAccessFormCode,
            id: res.data.data.records[0].id,
            formId: config.grantAccessFormId,
            expireTimestamp: res.data.data.records[0].dataContent.expireTimestamp
          }
          this.$refs.userFormDialog.visible = true
        } else {
          this.userFormDialogData = { isNew: true, formCode: config.grantAccessFormCode, formTitle: 'Grant Access' }
          this.$refs.userFormDialog.visible = true
        }
      }).finally(() => {
        this.grantAccessLoading = false
      })
    },
    async saveClientPortalSetting (val) {
      const params = {
        keyword: 'role_manage_grant_access',
        type: 'ROLE_MANAGE_GRANT_ACCESS',
        value: val
      }
      const { data: response } = await setSetting(params)
      if (response.code !== 0) {
        this.$message.error(response.msg)
        throw response.msg
      }
      this.$message.success(response.msg)
    },
    async getClientPortalSetting () {
      const params = {
        keyword: 'role_manage_grant_access'
      }
      const { data: response } = await fetchSetting(params)

      const value = get(response, 'data.value')
      this.checked = value === 'true'
    },
    isDisabledSelectable (row, index) {
      if (row.id === '0') {
        return true
      } else {
        return false
      }
    },
    addOrUpdateHandle (id, roleId, view) {
      // if (id === '0') {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.dataForm.id = roleId
        if (view) this.$refs.addOrUpdate.formCode = view
        else this.$refs.addOrUpdate.formCode = ''
        this.$refs.addOrUpdate.init()
      })
      // } else {
      //   return this.$message({
      //     message: this.$t('prompt.nopermission'),
      //     type: 'warning'
      //   })
      // }
    },
    deleteHandleSelf (id, roleId) {
      let deleteRoleList = []
      if (id && roleId) {
        deleteRoleList.push({
          id, roleId
        })
      } else {
        try {
          if (this.dataListSelections.length <= 0) {
            return this.$message({
              message: this.$t('prompt.deleteBatch'),
              type: 'warning'
            })
          }
        } catch (error) { }
        for (let i = 0; i < this.dataListSelections.length; i++) {
          const element = this.dataListSelections[i]
          deleteRoleList.push({
            id: element.id,
            roleId: element.roleId
          })
        }
      }
      this.$interface.system.deleteClientOrDefaultRoleListApi({ data: deleteRoleList })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            if(res.code === 10052) {
              return this.$showErrorWithAssetList(res)
            }
            return this.$message.error(res.msg)
          }
          this.$message.success(res.msg)
          this.query()
        })
        .catch(e => { this.$message.error(e.msg) })
    }
  }
}
</script>
<style lang="scss" scoped>
.grantBtnGroup {
  display: flex;
  align-items: center;
  border: 1px solid #dcdfe6;
  background: #fff;
  border-radius: 3px;
  padding: 0 15px;
  height: 32px;
  .grantBtn {
    cursor: pointer;
  }
  .disable {
    cursor: not-allowed;
  }
  i {
    margin: 0 15px;
  }
}
</style>
